package com.inspur.xiaoju.service.impl;

import com.inspur.xiaoju.dto.CreateWorkspaceMemberDto;
import com.inspur.xiaoju.dto.DeleteWorkspaceMemberDto;
import com.inspur.xiaoju.dto.UpdateWorkspaceMemberDto;
import com.inspur.xiaoju.exception.BusinessException;
import com.inspur.xiaoju.model.WorkspaceMember;
import com.inspur.xiaoju.repository.WorkspaceMemberRepository;
import com.inspur.xiaoju.service.WorkspaceMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WorkspaceMemberServiceImpl implements WorkspaceMemberService {

    @Autowired
    private WorkspaceMemberRepository workspaceMemberRepository;
    
    @Autowired
    private MongoTemplate mongoTemplate;
    
    @Override
    public WorkspaceMember create(CreateWorkspaceMemberDto createDto) {
        WorkspaceMember member = new WorkspaceMember();
        member.setWorkspaceId(createDto.getWorkspaceId());
        member.setUserId(createDto.getUserId());
        member.setRole(createDto.getRole());
        
        Date now = new Date();
        member.setCreatedAt(now);
        member.setUpdatedAt(now);
        
        return workspaceMemberRepository.save(member);
    }
    
    @Override
    public Map<String, Object> batchCreate(String workspaceId, List<Map<String, String>> members, String creator, String creatorId) {
        if (members.isEmpty()) {
            return Collections.singletonMap("insertedCount", 0);
        }
        
        List<WorkspaceMember> membersToInsert = new ArrayList<>();
        Date now = new Date();
        
        for (Map<String, String> member : members) {
            WorkspaceMember workspaceMember = new WorkspaceMember();
            workspaceMember.setWorkspaceId(workspaceId);
            workspaceMember.setUserId(member.get("userId"));
            workspaceMember.setRole(member.get("role"));
            workspaceMember.setCreator(creator);
            workspaceMember.setCreatorId(creatorId);
            workspaceMember.setCreatedAt(now);
            workspaceMember.setUpdatedAt(now);
            
            membersToInsert.add(workspaceMember);
        }
        
        List<WorkspaceMember> inserted = workspaceMemberRepository.saveAll(membersToInsert);
        return Collections.singletonMap("insertedCount", inserted.size());
    }
    
    @Override
    public List<WorkspaceMember> findAllByUserId(String userId) {
        return workspaceMemberRepository.findByUserId(userId);
    }
    
    @Override
    public List<WorkspaceMember> findAllByWorkspaceId(String workspaceId) {
        return workspaceMemberRepository.findByWorkspaceId(workspaceId);
    }
    
    @Override
    public WorkspaceMember findOne(String workspaceId, String userId) {
        return workspaceMemberRepository.findByWorkspaceIdAndUserId(workspaceId, userId)
                .orElseThrow(() -> new BusinessException(404, "工作区成员不存在"));
    }
    
    @Override
    public Map<String, Object> updateRole(UpdateWorkspaceMemberDto updateDto, String operator, String operatorId) {
        Query query = new Query(Criteria.where("workspaceId").is(updateDto.getWorkspaceId())
                .and("userId").is(updateDto.getUserId()));
        
        Update update = new Update()
                .set("role", updateDto.getRole())
                .set("operator", operator)
                .set("operatorId", operatorId)
                .set("updatedAt", new Date());
        
        com.mongodb.client.result.UpdateResult result = mongoTemplate.updateFirst(query, update, WorkspaceMember.class);
        
        return Collections.singletonMap("modifiedCount", result.getModifiedCount());
    }
    
    @Override
    public Map<String, Object> deleteMember(DeleteWorkspaceMemberDto deleteDto) {
        workspaceMemberRepository.deleteByWorkspaceIdAndUserId(deleteDto.getWorkspaceId(), deleteDto.getUserId());
        return Collections.singletonMap("deletedCount", 1);
    }
    
    @Override
    public List<WorkspaceMember> batchSearchByWorkspace(List<String> workspaceIds) {
        return workspaceMemberRepository.findByWorkspaceIdIn(workspaceIds);
    }
}